<template>
  <div>
    <div style="margin-bottom: 10px">
      <!-- <div class="img2">
        <img
          src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=375778612,941464112&fm=26&gp=0.jpg"/>
      </div> -->

      <div class="cen-content" style="text-align: center">
        <span><b>用 户 管 理</b></span>
        <div class="new_btn">
          <el-button
            @click="Upload"
            style="
              width: 70px;
              background-color: #56c4bd;
              color: white;
              font-size: 18px;
              border-radius: 10px;
            "
            title="点击有(填)惊(信)喜(息)"
            >新 增</el-button
          >
        </div>
      </div>

      <!-- <div class="lbgif1">
        <img
          src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2484079327,2011002287&fm=26&gp=0.jpg"/>
      </div> -->
      <el-dialog
        :title="settitle"
        :visible.sync="dialog_set"
        width="40%"
        style="margin-top: 90px"
      >
        <!-- {{ Number_user_id }} -->
        <el-form label-width="100px">
          <el-form-item label="">
            <el-radio-group v-model="Number_user" size="medium">
              <el-radio label="教师" border></el-radio>
              <el-radio border label="管理员"></el-radio>
              <el-radio border label="学生"></el-radio>
              <el-radio border label="家长"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item size="large">
            <el-button type="primary" @click="save_set">确定</el-button>
            <el-button @click="dialog_set = false">取消</el-button>
          </el-form-item>

          <div class="footer2" style="text-align: center">
            <span style="color: red"
              >注：设置为管理员的用户
              即可通过自己的用户名和密码登录该平台！</span
            >
          </div>
        </el-form>
      </el-dialog>
    </div>

    <div class="content">
      <el-table
        :data="data.list"
        :model="data.list"
        style="width: 100%"
        :header-cell-style="getRowClass"
        :cell-style="rowStyle"
      >
        <el-table-column prop="id" label="ID" width="130"> </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
        ></el-table-column>
         <el-table-column
          prop="password"
          label="密码"
          width="150"
        ></el-table-column>
        <el-table-column prop="realname" label="姓名" width="150"> </el-table-column>
        <el-table-column
          prop="gender"
          label="性别"
          width="130"
        ></el-table-column>
        <el-table-column prop="telephone" label="手机号" width="150">
        </el-table-column>
        <el-table-column
          prop="birth"
          label="出生日期"
          width="180"
          :formatter="fmt"
        ></el-table-column>
        <el-table-column prop="roles[0].name" label="职位" width="150">
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              @click="delete_data(scope.row.id)"
              type="text"
              size="small"
            >
              删 除
            </el-button>

            <el-button type="text" size="small" @click="change_data(scope.row)">
              修改
            </el-button>
            <el-button @click="set_user(scope.row.id)" type="text"
              >用户授权</el-button
            >
           
          </template>
        </el-table-column>
      </el-table>


      <!--新增-修改 模态框 -->
      <el-dialog :title="title" :visible.sync="dialog_content" width="50%">
        <!-- {{ content }} -->
        <!-- {{ checkPass }} -->
        <el-form
          ref="form"
          :model="content"
          label-width="100px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="用户" prop="username">
            <el-input v-model="content.username" placeholder="用户名不能重复"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="content.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="checkPass"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="content.email"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="content.realname"></el-input>
          </el-form-item>

          <el-form-item label="性别">
            <el-radio-group v-model="content.gender" size="medium">
              <el-radio border label="男"></el-radio>
              <el-radio border label="女"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="手机号码" prop="telephone">
            <el-input v-model="content.telephone"></el-input>
          </el-form-item>

          <el-form-item prop="date" label="日期">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="content.birth"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>

          <el-form-item size="large">
            <el-button type="primary" @click="saveAndistitle">确定</el-button>
            <el-button @click="dialog_content = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!-- 分页按钮 -->
    <div style="text-align: center">
      <br />
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="obj.pageSize"
        :current-page="obj.page"
        @current-change="change"
        :total="data.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import moment from "moment";

var m;
var user_id;
var user_username;
export default {
  data() {
    //验证信息
    var pas;
    var check_username = (rule, value, callback) => {
      if (!value) {
        m = 0;
        callback(new Error("用户名不能为空"));
      } else if (value.length < 2 || value.length > 9) {
        m = 0;
        callback(new Error("用户名长度必须为2~9个字符"));
      } else {
        m = 1;
        callback();
      }
    };
    var check_password1 = (rule, value, callback) => {
      if (!value) {
        m = 0;

        callback(new Error("密码不能为空"));
      } else if (value.length < 6 || value.length > 15) {
        m = 0;

        callback(new Error("密码长度必须为6~15个字符"));
      } else {
        pas = value;
        callback();
        m = 1;
      }
      // else{
      //   if (this.checkPass !== '') {
      //       this.checkPass.check_password1('checkPass');
      //     }
      // }
    };
    var check_password2 = (rule, value, callback) => {
      value = this.checkPass;

      if (!value) {
        m = 0;

        callback(new Error("请再次输入密码"));
      } else if (value != pas) {
        m = 0;

        callback(new Error("两次输入密码不一致!"));
      } else {
        m = 1;

        callback();
      }
    };

    var validateEmail = (rule, value, callback) => {
      const emailReg = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})$/;
      if (!value) {
        m = 0;

        return callback(new Error("邮箱不能为空!!"));
      }
      setTimeout(() => {
        if (!emailReg.test(value)) {
          m = 0;

          return callback(new Error("邮箱格式错误"));
        } else {
          m = 1;
          callback();
        }
      }, 100);
    };

    var check_realname = (rule, value, callback) => {
      const realnameReg = /^([a-zA-Z\u4e00-\u9fa5\·]{2,10})$/;
      if (!value) {
        m = 0;

        return callback(new Error("真实姓名不能为空!!"));
      }
      setTimeout(() => {
        if (!realnameReg.test(value)) {
          m = 0;

          return callback(new Error("您的真实姓名格式错误,请输入英文或汉字!"));
        } else {
          m = 1;

          callback();
        }
      }, 100);
    };

    var validatePhone = (rule, value, callback) => {
      const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!value) {
        m = 0;

        return callback(new Error("手机号码不能为空!!"));
      }
      setTimeout(() => {
        if (!phoneReg.test(value)) {
          m = 0;

          return callback(new Error("手机号码格式错误"));
        } else {
          m = 1;

          callback();
        }
      }, 100);
    };

    return {
      obj: {
        page: 1,
        pageSize: 9,
      },
      obj_username: {
        page: 1,
        pageSize: 1000000,
      },
      
      img_url: "",
      checkPass: "",
      Number_user: "",
      Number_user_id: "",
      dialog_set: false,
      all_username: [],
      dialog_content: false,
      dialog_seek:false,
      seek_data:'',
      content: {},
      title: "用户信息",
      settitle:'设置权限',
      message: "",
      rules: {
        username: [{ validator: check_username, trigger: "blur" }],
        password: [{ validator: check_password1, trigger: "blur" }],
        checkPass: [{ validator: check_password2, trigger: "blur" }],
        realname: [{ validator: check_realname, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        telephone: [{ validator: validatePhone, trigger: "blur" }],
      },
    };
  },
  // 过滤器 - 处理日期格式
  filters: {
    dateFMT(str) {
      // var res = moment(str).format('YYYY-MM-DD HH:mm:ss');
      // return res;
      return moment(str).format("YYYY-MM-DD HH:mm:ss");
    },
  },
  //监听
  watch: {
    obj: {
      handler: function () {
        this.find_user(this.obj);
      },
      deep: true,
    },
  },
  //计算
  computed: {
    // 从usermanagement.js文件的state中获取data / data_username变量
    ...mapState("usermanagement", ["data", "data_username"]),
  },
  //执行方法
  created() {
    this.find_user(this.obj);
  },
  methods: {
    // 从usermanagement.js文件的actions 中获取  方法
    ...mapActions("usermanagement", [
      "find_user",
      "find_isUser",
      "delete_user",
      "change_user",
      "set_authority",
      "set_rivilege",
      "seek_user",
    ]),

    delete_data(val) {
      this.delete_user({ id: val }).then((res) => {
        if (res.status == 200) {
          //   alert("删除成功！！！");
          this.open("删除成功！！！", "success");

          this.find_user(this.obj);
        }
      });
    },

    //新增按钮
    Upload() {
      //打开模态框
      this.dialog_content = true;
      //把内容清空
      this.content = {};
    },

    // 修改按钮
    change_data(val) {
      // 1. 弹出模态框
      this.dialog_content = true;

      // 2. 将当前行数据 转为json格式
      this.content = JSON.parse(JSON.stringify(val));

      this.find_isUser(this.obj_username).then(() => {
        if (this.data_username) {
          let i = this.data_username.total;
          //   console.log(i);
          this.data_username.list.forEach((val, index) => {
            this.all_username[index] = val.username;
          });

          this.all_username.forEach((val, index) => {
            if (val == this.content.username) {
              delete this.all_username[index];
            }
          });
        }
      });
    },

    set_user(val) {
      user_id = val;
      this.dialog_set = true;
    },

    //给用户设置权限 (1.教师 2.管理员 6.学生 7.家长)
    save_set() {
      if (this.Number_user == "教师") {
        this.Number_user_id = 1;
      } else if (this.Number_user == "管理员") {
        this.Number_user_id = 2;
        this.set_rivilege(user_id).then((res) => {});
      } else if (this.Number_user == "学生") {
        this.Number_user_id = 6;
      } else {
        this.Number_user_id = 7;
      }

      if (this.Number_user) {
        console.log({ roles: this.Number_user_id, id: user_id });
        this.set_authority({ roles: this.Number_user_id, id: user_id }).then(
          (res) => {
            if (res.status == 200) {
              this.open("设置成功！！！", "success");
            }
            this.find_user(this.obj);
            this.dialog_set = false;
          }
        );
        this.Number_user = "";
        this.Number_user_id = "";
      }
    },

    //更新信息
    saveOrchange() {
      //把日期转为 时间戳形式
      if (this.content.birth) {
        this.content.birth = new Date(this.content.birth).getTime();
      } else {
        this.content.birth = " ";
      }

      console.log(this.content.birth);

      this.change_user(this.content).then((res) => {
        if (res.status == 200) {
          //   alert("更新成功！！！");
          this.open("更新成功！！！", "success");

          this.find_user(this.obj);
        } else {
          //   alert("更新失败！！");
          this.open("更新失败！！！", "error");
        }
      });
    },

    // //查看用户详细信息
    // seek(val) {
    //   this.dialog_seek = true;
    //   this.obj_seekuser.username = val;
    //   this.seek_user(this.obj_seekuser).then((res)=>{
    //     this.seek_data = res.data.list
    //   })
    // },

    //判断用户名是否已存在 and 更新信息
    saveAndistitle() {
      var a = 0;

      //关闭模态框
      this.dialog_content = false;

      this.all_username.forEach((val, index) => {
        if (val == this.content.username) {
          //   alert("用户名已存在！！！");
          this.open("用户名已存在！！！", "warning");
          a = 1;
        }
      });

      // 1.用户名是否已存在 2.用户信息是否都填好了   不存在且填好 则执行更新信息方法
      if (a == 0 && m == 1) {
        this.saveOrchange();
      } else {
        this.open("用户信息未填完整或填写的信息格式不符合", "warning");
      }
    },

    //把时间戳转为 日期格式
    fmt(row, column) {
      return moment(row.birth).format("YYYY-MM-DD");
    },

    // 页码改变
    change(page) {
      this.obj.page = page;
    },

    //提示框
    open(message, type) {
      this.$message({
        showClose: true,
        message: message,
        type: type,
      });
    },

    //设置样式
    rowStyle({ row, column, rowIndex, columnIndex }) {
      //设置表格每行间隔颜色
      if (rowIndex % 2 === 0) {
        return "background:#2A3056;border:none;color: #FFFFFF;";
      }
      if (rowIndex % 2 === 1) {
        return "background:#2E335E;border:none;color: #FFFFFF;";
      }
    },
    //设置表头背景颜色
    getRowClass({ row, column, rowIndex, columnIndex }) {
      return "background:#363C74;border:none;color: #FFFFFF;";
    },
  },
};
</script>

<style scoped>
.lbgif1 {
  display: inline-block;
  right: 0;
}
.lbgif1 img {
  width: 230px;
  height: 190px;
}
.img2 {
  display: inline-table;
  vertical-align: top;
  height: 190px;
  border: indigo 1px solid;
  left: 0;
}
.img2 img {
  width: 300px;
  height: 150px;
}
.cen-content {
  width: 100%;
  height: 190px;
  text-align: center;
  vertical-align: top;
  display: inline-block;
  /* margin-bottom: 20px;   */
  /* border: 1px red solid;   */
  /* background-size: 100%; */
  background: url("../..//icons/svg/login_bg.gif") no-repeat;
  background-size: 100%;
  position: relative;
}

.cen-content span {
  display: inline-block;
  margin-top: 45px;
  font-size: 50px;
  color: indianred;
  font-style: italic;
}
.new_btn {
  /* margin-bottom: 10px; */
  left: 50px;
  bottom: 5px;
  position: absolute;
}
/deep/.el-dialog__header {
  width: 150px;
  margin: 0 auto;
}
/deep/.el-radio-group label:first-child {
  margin-left: 10px;
}
/deep/.el-radio-group label:nth-child(2) {
  margin-right: 0px;
}
/deep/.el-radio {
  width: 98px;
  background: burlywood;
}

/deep/.el-dialog__title {
  font-weight: bolder;
  font-size: 25px;
  font-style: italic;
  color: cadetblue;
}
/deep/.el-dialog {
  border-radius: 150px;
  background-color: bisque;
}
/deep/.el-form {
  /* margin: 0 auto; */
}
/deep/.el-form-item {
  width: 500px;
  margin-bottom: 20px;
  margin-left: auto;
  margin-right: auto;
}
/deep/.el-table th > .cell {
  font-size: 18px;
}
/* /deep/.is-leaf{
    background-color: #2E335E;
}  */
/deep/.el-table .cell {
  text-align: center;
  font-size: 15px;
}

/deep/.el-form-item__content {
  width: 300px;
}
/deep/.el-input {
  width: 300px;
}
/deep/.el-input__inner {
  width: 300px;
  padding: 0 15px;
}
/deep/[data-v-5dcbf221] .el-input__inner {
  padding: 0 28px;
}
/deep/.el-icon-date::before {
  vertical-align: middle;
}
/deep/.el-form-item--large {
  text-align: center;
}
/deep/.el-form-item__content {
  margin-left: 0px;
  text-align: center;
}
</style>